import axios from 'axios'
import { Loading, Message, MessageBox } from 'element-ui'
import store from './store/index'
import router from './router/index'
import sessionStorage from './assets/js/storage/sessionStorage'

if (!store.state.token) {
  store.commit('token', sessionStorage.getItem('token'))
}
// console.log(process.env.NODE_ENV)
// const API_PROXY_PREFIX = 'http://120.24.147.235:8087'
// const baseURL = process.env.NODE_ENV === 'production' ? process.env.VUE_APP_API_BASE_URL : API_PROXY_PREFIX
const baseURL = process.env.VUE_APP_API_BASE_URL

// axios 配置
const http = axios.create({
  // 测试服务器120.24.147.235:8087  http://192.168.30.104:8087
  //   baseURL:'http://api.5eck.cn',//正式
  // baseURL: 'http://120.24.147.235:8087', //测试
  baseURL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  },
  transformRequest: [
    function (data, headers) {
      headers.Authorization = 'Bearer ' + store.state.token
      if (store.state.token == 'null' || headers.Authorization == 'Bearer ') {
        headers.Authorization = ''
      }
      if (headers['Content-Type'] === 'multipart/form-data') {
        return data
      } else {
        return JSON.stringify(data)
      }
    }
  ]
})

var loadingInstance

function startLoading () {
  // 使用Element loading-start 方法
  loadingInstance = Loading.service({
    lock: true,
    text: '正在请求数据……',
    background: 'rgba(255, 255, 255, 0.3)'
  })
}

function endLoading () {
  // 使用Element loading-close 方法
  loadingInstance.close()
}
// 那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
// 声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
// 调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}
// 设置全局的请求次数，请求的间隙
axios.defaults.retry = 3 // 请求次数
axios.defaults.retryDelay = 2000 // 请求间隙
// 请求拦截器
http.interceptors.request.use(
  (config) => {
    if (process.env.NODE_ENV === 'development') {
      // const { method } = config;
    }
    if (config.headers.isLoading !== false) {
      // 如果配置了isLoading: false，则不显示loading
      showFullScreenLoading()
    }

    return config
  },
  (error) => {
    endLoading()
    Message.error({
      message: '请求失败'
    })
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  (res) => {
    // loadingInstance.close();
    tryHideFullScreenLoading()
    if (res.data.code == 102) {
      router.replace({
        path: '/login',
        query: {
          // redirect: router.currentRoute.fullPath,
        }
      })
    }

    if (res.config.responseType == 'blob') {
      return res
    } else {
      return res.data
    }
  },
  (error) => {
    loadingInstance.close()
    tryHideFullScreenLoading()
    if (error && error.response) {
      switch (error.response.status) {
        // 401 token失效
        case 102:
          MessageBox.alert('身份信息已过期，请重新登陆', '提示', {
            confirmButtonText: '重新登陆',
            showClose: false,
            type: 'error',
            callback: function () {
              router.replace({
                path: '/login',
                query: {
                  redirect: router.currentRoute.fullPath
                }
              })
            }
          })
          break
        // 403 服务器拒绝访问
        case 403:
          router.push('/error/403')
          break

        // 404 访问的资源不存在
        case 404:
          // router.push('/error/404');
          break

        // 500 服务器错误
        case 500:
          router.push('/error/500')
          break
      }
    }
  }
)

// 通用下载方法
export function download (url, params, filename) {
  return http
    .post(url, params, {
      transformRequest: [
        (params, headers) => {
          headers.Authorization = 'Bearer ' + store.state.token
          return JSON.stringify(params)
        }
      ],
      responseType: 'blob',
      timeout: 60000
    })
    .then((data) => {
      if (data.status == 200) {
        const content = data.data
        const blob = new Blob([content], {
          type:
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'
        })
        // console.log(data);
        const contentDisposition = data.headers['content-disposition']
        let filename = ''
        if (
          contentDisposition + '' != '' &&
          contentDisposition + '' != 'undefined' &&
          contentDisposition + '' != 'null'
        ) {
          filename = window.decodeURI(contentDisposition.split('=')[1], 'UTF-8')
        } else {
          filename = '报表'
        }
        if ('download' in document.createElement('a')) {
          const elink = document.createElement('a')
          elink.download = filename // 下载的名称

          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)

          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href)
          document.body.removeChild(elink)
        } else {
          navigator.msSaveBlob(blob, filename)
        }
      } else {
        this.$message.error(data.data)
      }
    })
    .catch((r) => {
      console.log(r)
    })
}

// 判断是否是数字
export function judgeIsNum (srt) {
  var pattern = /^\d+$/g // 正则表达式 ^ 代表从开始位置起   $ 末尾   + 是连续多个  \d 是数字的意思   不懂的话可以去百度正则表达式表
  var result = srt.match(pattern) // match 是匹配的意思   用正则表达式来匹配
  if (result == null) {
    return false
  } else {
    return true
  }
}

export function downloadlink (url) {
  const protocol = location.protocol
  let resultUrl = url
  if(protocol === 'https:'){
    resultUrl = url.replace(`http:`, `${protocol}`);
  }
  var iframe = document.createElement('iframe')
  // iframe.style.display = 'none'
  iframe.src = resultUrl
  iframe.name = url;
  document.body.appendChild(iframe)
  // console.log('iframe',iframe)
  
}

export default http
